import { useState, useEffect } from 'react';

export type Breakpoint = 'mobile' | 'tablet' | 'desktop';

/**
 * useBreakpoint Hook
 * 返回当前断点（mobile/tablet/desktop）
 *
 * 断点定义：
 * - mobile: < 768px
 * - tablet: 768px - 1024px
 * - desktop: >= 1024px
 */
export const useBreakpoint = (): Breakpoint => {
  const [breakpoint, setBreakpoint] = useState<Breakpoint>(() => {
    if (typeof window === 'undefined') return 'desktop';
    const width = window.innerWidth;
    if (width < 768) return 'mobile';
    if (width < 1024) return 'tablet';
    return 'desktop';
  });

  useEffect(() => {
    // 防抖优化
    let timeoutId: NodeJS.Timeout;

    const handleResize = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        const width = window.innerWidth;
        if (width < 768) {
          setBreakpoint('mobile');
        } else if (width < 1024) {
          setBreakpoint('tablet');
        } else {
          setBreakpoint('desktop');
        }
      }, 300); // 300ms 防抖
    };

    window.addEventListener('resize', handleResize);
    return () => {
      clearTimeout(timeoutId);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return breakpoint;
};
